package com.gbiac.modules.monitor.controller;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gbiac.modules.monitor.entity.*;
import com.gbiac.modules.monitor.param.EnableSeatAllParam;
import com.gbiac.modules.monitor.param.EnableSeatParam;
import com.gbiac.modules.monitor.param.ForceCheckOutAllParam;
import com.gbiac.modules.monitor.param.ForceCheckOutParam;
import com.gbiac.modules.monitor.service.*;
import com.gbiac.modules.monitor.vo.SeatUserVo;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.oConvertUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: 席位管理
 * @Author: jeecg-boot
 * @Date:   2024-11-30
 * @Version: V1.0
 */
@Api(tags="席位管理")
@RestController
@RequestMapping("/monitor/seat")
@Slf4j
public class SeatController extends JeecgController<Seat, ISeatService> {
	@Autowired
	private ISeatService seatService;

	@Resource
	private ISeatUserService seatUserService;
	@Resource
	private ISysBaseAPI sysBaseAPI;
	@Resource
	private IUserCheckInService userCheckInService;
	@Resource
	private IUserLeaveService userLeaveService;
	@Resource
	private IUserSeatService userSeatService;
	@Resource
	private IEquipmentService equipmentService;

	/**
	 * 分页列表查询
	 *
	 * @param seat
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "席位管理-分页列表查询")
	@ApiOperation(value="席位管理-分页列表查询", notes="席位管理-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<Seat>> queryPageList(Seat seat,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<Seat> queryWrapper = QueryGenerator.initQueryWrapper(seat, req.getParameterMap());
		Page<Seat> page = new Page<Seat>(pageNo, pageSize);
		IPage<Seat> pageList = seatService.page(page, queryWrapper);
		// 查询设备信息
		IPage<Seat> result = pageList.convert((item) -> {
			if (StringUtils.isBlank(item.getEquipmentId())) {
				return item;
			}
			Equipment equipment = equipmentService.getById(item.getEquipmentId());
			if (equipment == null) {
				return item;
			}
			item.setEquipment(equipment);
			return item;
		});
		return Result.OK(result);
	}

	 @ApiOperation(value="席位管理-分页列表查询席位用户状态", notes="席位管理-分页列表查询席位用户状态")
	 @GetMapping(value = "/listSeatUser")
	 public Result<IPage<SeatUserVo>> listSeatUser(Seat seat,
												   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
												   HttpServletRequest req) throws ParseException {
		 QueryWrapper<Seat> queryWrapper = QueryGenerator.initQueryWrapper(seat, req.getParameterMap());
		 Page<Seat> page = new Page<Seat>(pageNo, pageSize);
		 IPage<Seat> pageList = seatService.page(page, queryWrapper);

		 // 查特情，只查当天的
		 List<UserLeave> userLeaveList = userLeaveService.list(new LambdaQueryWrapper<UserLeave>()
				 .ge(UserLeave::getStartTime, DateUtils.parseDate(DateUtils.formatDate(new Date(), "yyyy-MM-dd") + " 00:00:00", "yyyy-MM-dd HH:mm:ss"))
				 .le(UserLeave::getStartTime, DateUtils.parseDate(DateUtils.formatDate(new Date(), "yyyy-MM-dd") + " 23:59:59", "yyyy-MM-dd HH:mm:ss"))
				 .orderByAsc(UserLeave::getStartTime)
		 );

		 IPage<SeatUserVo> result = pageList.convert((item) -> {
			 SeatUserVo seatUserVo = new SeatUserVo(item);
			 if ("0".equals(item.getDisable())) {
				 // 席位未禁用时，找出对应的特情信息
				 seatUserVo.setUserLeaveList(
						 userLeaveList.stream().filter((userLeave) -> {
							 long count = userSeatService.count(new LambdaQueryWrapper<UserSeat>().eq(UserSeat::getUserId, userLeave.getUserId()).eq(UserSeat::getSeatId, seatUserVo.getId()));
							 return count > 0;
						 }).collect(Collectors.toList())
				 );
			 }
			 SeatUser seatUser = seatUserService.getOne(new LambdaQueryWrapper<SeatUser>().eq(SeatUser::getSeatId, item.getId()));
			 if (seatUser == null || StringUtils.isBlank(seatUser.getUserId())) {
				 return seatUserVo;
			 }
			 LoginUser user = sysBaseAPI.getUserById(seatUser.getUserId());
			 seatUserVo.setUser(user);
			 // 打卡记录
			 List<UserCheckIn> userCheckInList = userCheckInService.list(new LambdaQueryWrapper<UserCheckIn>()
					 .eq(UserCheckIn::getUserId, user.getId())
					 .eq(UserCheckIn::getSeatId, item.getId())
					 .ge(UserCheckIn::getCheckInTime, seatUser.getCheckInTime())
					 .orderByDesc(UserCheckIn::getCreateTime));
			 // 计算在岗时长(毫秒)
			 long duration = userCheckInList.stream().mapToLong((userCheckIn) -> {
				 Date checkOutTime = userCheckIn.getCheckOutTime();
				 if (checkOutTime == null) {
					 checkOutTime = new Date();
				 }
				 return checkOutTime.getTime() - userCheckIn.getCheckInTime().getTime();
			 }).sum();
			 // 分钟
			 seatUserVo.setDuration(new BigDecimal(duration).divide(new BigDecimal(1000), 2, RoundingMode.HALF_UP).divide(new BigDecimal(60), 2, RoundingMode.HALF_UP));
			 seatUserVo.setUserCheckIn(userCheckInList.get(0));
			 return seatUserVo;
		 });
		 return Result.OK(result);
	 }
	
	/**
	 *   添加
	 *
	 * @param seat
	 * @return
	 */
	@AutoLog(value = "席位管理-添加")
	@ApiOperation(value="席位管理-添加", notes="席位管理-添加")
	@RequiresPermissions("monitor:gbiac_seat:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody Seat seat) {
		seatService.save(seat);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param seat
	 * @return
	 */
	@AutoLog(value = "席位管理-编辑")
	@ApiOperation(value="席位管理-编辑", notes="席位管理-编辑")
	@RequiresPermissions("monitor:gbiac_seat:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody Seat seat) {
		seatService.updateById(seat);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "席位管理-通过id删除")
	@ApiOperation(value="席位管理-通过id删除", notes="席位管理-通过id删除")
	@RequiresPermissions("monitor:gbiac_seat:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		seatService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "席位管理-批量删除")
	@ApiOperation(value="席位管理-批量删除", notes="席位管理-批量删除")
	@RequiresPermissions("monitor:gbiac_seat:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.seatService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "席位管理-通过id查询")
	@ApiOperation(value="席位管理-通过id查询", notes="席位管理-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<Seat> queryById(@RequestParam(name="id",required=true) String id) {
		Seat seat = seatService.getById(id);
		if(seat==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(seat);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param seat
    */
    @RequiresPermissions("monitor:gbiac_seat:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Seat seat) {
        return super.exportXls(request, seat, Seat.class, "席位管理");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("monitor:gbiac_seat:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, Seat.class);
    }



	 @AutoLog(value = "席位管理-启用席位")
	 @ApiOperation(value="席位管理-启用席位", notes="席位管理-启用席位")
	 @PostMapping(value = "/enableSeat")
	 public Result<?> enableSeat(@Valid @RequestBody EnableSeatParam param) {
		 seatService.enableSeat(param.getSeatId());
		 return Result.ok("操作成功");
	 }

	 @AutoLog(value = "席位管理-启用所有席位")
	 @ApiOperation(value="席位管理-启用所有席位", notes="席位管理-启用所有席位")
	 @PostMapping(value = "/enableSeatAll")
	 public Result<?> enableSeatAll(@Valid @RequestBody EnableSeatAllParam param) {
		 seatService.enableSeatAll(param.getOrgCode());
		 return Result.ok("操作成功");
	 }

}
